package com.yuanfeng.activity.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yuanfeng.activity.dto.DiscountBaseDetailQueryDTO;
import com.yuanfeng.activity.dto.DiscountGoodsAddParamDTO;
import com.yuanfeng.activity.dto.DiscountGoodsListDTO;
import com.yuanfeng.activity.entity.ActivityDiscountBaseEntity;
import com.yuanfeng.activity.entity.ActivityDiscountGoodsEntity;
import com.yuanfeng.activity.feign.GoodsServiceClient;
import com.yuanfeng.activity.mapper.ActivityDiscountBaseMapper;
import com.yuanfeng.activity.mapper.ActivityDiscountGoodsMapper;
import com.yuanfeng.activity.service.ActivityDiscountGoodsService;
import com.yuanfeng.activity.vo.*;
import com.yuanfeng.commoms.aspect.UserPermissionsResult;
import com.yuanfeng.commoms.aspect.UserService;
import com.yuanfeng.commoms.config.PermissionsConstant;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.excel.ExcelsUtil;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.activity.AppDiscountGoodsQueryResultVO;
import com.yuanfeng.commoms.vo.activity.CheckDiscountLimitResultVO;
import com.yuanfeng.commoms.vo.activity.ModularGoodsVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName ActivityDiscountGoodsServiceImpl
 * @Description 限时折扣商品表
 * @Author cyp
 * @Date 2023-05-25 14:10:09
 * @Version 1.0
 **/
@Service
public class ActivityDiscountGoodsServiceImpl extends ServiceImpl<ActivityDiscountGoodsMapper, ActivityDiscountGoodsEntity>
        implements ActivityDiscountGoodsService {

    @Autowired
    private ActivityDiscountGoodsMapper activityDiscountGoodsMapper;

    @Autowired
    private ActivityDiscountBaseMapper activityDiscountBaseMapper;

    @Autowired
    private GoodsServiceClient goodsServiceClient;

    @Override
    public AppDiscountGoodsQueryResultVO selectDiscountByGoodsId(Integer goodsId) {
        return this.baseMapper.selectDiscountByGoodsId(goodsId);
    }

    @Override
    public CheckDiscountLimitResultVO queryDiscountInfoByGoodsId(Integer goodsId) {
        return this.baseMapper.queryDiscountInfoByGoodsId(goodsId);
    }

    @Override
    public AppDiscountGoodsQueryResultVO selectDiscountByGoodsIdAndTime(Integer goodsId) {
        AppDiscountGoodsQueryResultVO vo = this.baseMapper.selectDiscountByGoodsIdAndTime(goodsId);
        if(vo == null){
            vo = this.baseMapper.selectDiscountByGoodsId(goodsId);
        }
        return vo;
    }

    @Override
    public ResponseResult queryDiscountLimitIndex(Map<String, Object> param) {
        String userInfoStr = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + param.get("token").toString());
        BigDecimal discount = null;
        if (null != userInfoStr) {
            UserInfoVO dto = JSON.parseObject(userInfoStr, UserInfoVO.class);
            discount = dto.getPlusDiscount();
        }
        List<DiscountGoodsListQueryResultVO> returnList = new ArrayList<>();
        List<DiscountGoodsListQueryResultVO> promotionGoodsList = this.baseMapper.queryDiscountLimitIndexGoods(param);
        if (CollectionUtils.isEmpty(promotionGoodsList)) {
            returnList = Lists.newArrayList();
        }else{
            for (DiscountGoodsListQueryResultVO discountGoodsListQueryResult : promotionGoodsList) {
                discountGoodsListQueryResult.setDiscountMember(discount);
            }

            Integer limitSize = (Integer) param.get("limitSize");
            int sumSize = promotionGoodsList.size();
            if(sumSize < limitSize){
                limitSize = sumSize;
            }
            int randNum;
            Random rand = new Random();
            for(int i=0; i<limitSize ; i++){
                sumSize = promotionGoodsList.size();
                randNum = rand.nextInt(sumSize);
                returnList.add(promotionGoodsList.get(randNum));
                promotionGoodsList.remove(promotionGoodsList.get(randNum));
            }

        }

        return ResponseResult.success(returnList);
    }

    @Override
    public ResponseResult checkDiscountLimit(Map<String, Object> param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.get("token").toString());
        if (null != userInfo) {
            String userId = userInfo.getUserId();
            List<Map<String,Object>> list = (List) param.get("list");
            List<Integer> commonIds = new ArrayList<>();
            List<Map<String,Object>> commonMapList = new ArrayList<>();
            for (Map<String, Object> map : list) {
                Integer commonId = (Integer) map.get("commonId");
                if (!commonIds.contains(commonId)){
                    commonIds.add(commonId);
                    commonMapList.add(map);
                }else{
                    for (Map<String, Object> stringObjectMap : commonMapList) {
                        if(stringObjectMap.get("commonId") == commonId){
                            Integer goodsNum = (Integer) stringObjectMap.get("goodsNum") + (Integer) map.get("goodsNum");
                            stringObjectMap.put("goodsNum",goodsNum);
                        }
                    }
                }
            }
            Integer flag = 0;
            for (Map<String, Object> stringObjectMap : commonMapList) {
                Integer commonId = (Integer) stringObjectMap.get("commonId");
                Integer goodsNum = (Integer) stringObjectMap.get("goodsNum");
//                Integer goodsId = (Integer) param.get("goodsId");
//                Integer goodsNum = param.get("goodsNum") == null ? 1 : (Integer) param.get("goodsNum");
                CheckDiscountLimitVO data = this.baseMapper.queryDiscountInfo(commonId);
                Integer count = null;
                if (null != data) {
                    Integer goodsUpperLimit = data.getGoodsUpperLimit();
                    Integer discountUpperTime = data.getDiscountUpperTime();
                    if (0 == goodsUpperLimit && 0 == discountUpperTime) {
                        flag = 1;
                        continue;
                    }
                    Calendar cal = Calendar.getInstance();
                    Date fdate = new Date();
                    cal.setTime(fdate);
                    cal.add(Calendar.DATE, -discountUpperTime);
                    fdate = cal.getTime();
                    // 获取当天的日期
                    LocalDate today = LocalDate.now();
                    // 设置当天的开始时间为00:00:00
                    LocalDateTime startOfDay = today.atStartOfDay();
                    // 设置当天的结束时间为23:59:59.999999999
                    LocalDateTime endOfDay = LocalDateTime.of(today, LocalTime.MAX);
                    param.put("fDate", fdate);
                    param.put("commonId", commonId);
                    param.put("discountId", data.getDiscountId());
                    param.put("userId", userId);
                    param.put("goodsPrice", data.getDiscountPrice());
                    param.put("goodsStartTime", startOfDay);
                    param.put("goodsEndTime", endOfDay);
                    count = this.baseMapper.queryOrderGoodsCount(param);
                    count = count == null ? 0 : count;
                    if ((count + goodsNum) > goodsUpperLimit) {
                        return ResponseResult.fail(BizCodeEnume.ACTIVITY_LIMIT_PURCHASE_LIMIT);
                    }
                } else {
                    return ResponseResult.fail(BizCodeEnume.ACTIVITY_ACTIVITY_ENDED);
                }
            }
            if(flag == 1){
                return ResponseResult.success("该商品不限购");
            }
            return ResponseResult.success(BizCodeEnume.ACTIVITY_NO_PURCHASE_LIMIT.getMsg());
        }else{
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);

        }
    }

    @Override
    public ResponseResult checkDiscountLimit2(Map<String, Object> param) {
        String token = (String) param.get("token");
        Integer commonId = (Integer) param.get("commonId");
        CheckDiscountLimitVO data = this.baseMapper.queryDiscountInfo(commonId);
        Integer count = null;
        String userId = null;
        if (null != token) {
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.get("token").toString());
            userId = userInfo.getUserId();
        }
        if (null != data) {
            Integer discountUpperTime = data.getDiscountUpperTime();
            Calendar cal = Calendar.getInstance();
            Date fdate = new Date();
            cal.setTime(fdate);
            cal.add(Calendar.DATE, -discountUpperTime);
            // 获取当天的日期
            LocalDate today = LocalDate.now();
            // 设置当天的开始时间为00:00:00
            LocalDateTime startOfDay = today.atStartOfDay();
            // 设置当天的结束时间为23:59:59.999999999
            LocalDateTime endOfDay = LocalDateTime.of(today, LocalTime.MAX);
            param.put("commonId", commonId);
            param.put("userId", userId);
            param.put("goodsStartTime", startOfDay);
            param.put("goodsEndTime", endOfDay);
            if(userId!=null){
                count = this.baseMapper.queryOrderGoodsCount(param);
            }
            count = count == null ? 0 : count;
            data.setBuyNum(count);
            return ResponseResult.success(data);
        }else{
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);

        }
    }

    @Override
    @Transactional
    public ResponseResult deleteDiscountBase(DiscountBaseDetailQueryDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_PROMOTION_DISCOUNT, param.getToken());

        if (userPermissionsResult.getFlag()) {

            List<Integer> commonIdList = activityDiscountGoodsMapper.selectDiscountGoods(param.getDiscountId());

            if (!org.springframework.util.CollectionUtils.isEmpty(commonIdList)) {
                // 获取其他正在进行的活动
                List<Integer> activeCommonIdList = activityDiscountGoodsMapper.selectActiveDiscountGoods(param.getDiscountId(),
                        commonIdList.get(0));
                if (org.springframework.util.CollectionUtils.isEmpty(activeCommonIdList)) {
                    goodsServiceClient.updateCommonIsXian2(commonIdList);
                }
            }
            activityDiscountGoodsMapper.deleteDiscountGoods(param.getDiscountId());
            activityDiscountBaseMapper.deleteByPrimaryKey(param.getDiscountId());
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(), BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success();
    }

    @Override
    @Transactional
    public ResponseResult deleteDiscountGoods(DiscountBaseDetailQueryDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_PROMOTION_DISCOUNT, param.getToken());

        if (userPermissionsResult.getFlag()) {
            Integer commonIsXian = 0;

            if (null != param.getCommonId()) {
                // 获取其他正在进行的活动
                List<Integer> activeCommonIdList = activityDiscountGoodsMapper.selectActiveDiscountGoods(param.getDiscountId(),
                        param.getCommonId());
                if (org.springframework.util.CollectionUtils.isEmpty(activeCommonIdList)) {
                    Map<String,Object> map = new HashMap<>();
                    map.put("commonIsXian",commonIsXian);
                    map.put("commonId",param.getCommonId());
                    goodsServiceClient.updateCommonIsXian(map);
                }

            }
            activityDiscountGoodsMapper.deleteDiscountGoods2(param);
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(), BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }

        return ResponseResult.success();
    }



    @Override
    @Transactional
    public ResponseResult addDiscountGoods(DiscountGoodsAddParamDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_PROMOTION_DISCOUNT, param.getToken());

        if (userPermissionsResult.getFlag()) {
            List<DiscountGoodsListDTO> discountGoodsList = param.getDiscountGoodsList();
            String shopId = userPermissionsResult.getShopId();

            // 查询店铺活动详情
            DiscountBaseDetailResultVO discountBase = activityDiscountBaseMapper
                    .selectDiscountBaseDetail2(param.getDiscountId());

            Integer commonId = null;

            // 校验商品是否存在或重复
            if (org.springframework.util.CollectionUtils.isEmpty(discountGoodsList)) {
                return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(), "无效必传参数：" + JSON.toJSONString(param));
            }

            Integer commonId2 = discountGoodsList.get(0).getCommonId();
            Integer flag = activityDiscountGoodsMapper.checkSpecNum(commonId2);
            if (flag.equals(1)) {
                return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.SPEC_REPEAT.getMsg()+JSON.toJSONString(param));
            }

            for (DiscountGoodsListDTO discountGoods : discountGoodsList) {
                commonId = discountGoods.getCommonId();

                DiscountGoodsAddParamDTO addGoods = new DiscountGoodsAddParamDTO();
                addGoods.setDiscountId(param.getDiscountId());

                addGoods.setDiscountName(discountBase.getDiscountName());
                addGoods.setDiscountTitle(discountBase.getDiscountTitle());
                addGoods.setDiscountExplain(discountBase.getDiscountExplain());
                addGoods.setGoodsStartTime(discountBase.getDiscountStartTime());
                addGoods.setGoodsEndTime(discountBase.getDiscountEndTime());
                addGoods.setGoodsUpperLimit(discountBase.getDiscountUpperLimit());
                addGoods.setGoodsLowerLimit(discountBase.getDiscountLowerLimit());
                addGoods.setDiscountGoodsState(discountBase.getDiscountState());

                addGoods.setDiscountUpperTime(discountBase.getDiscountUpperTime());
                addGoods.setPreStartHour(discountBase.getPreStartHour());
                if(null != discountBase.getPreStartHour() && 0 != discountBase.getPreStartHour()){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Calendar cal = Calendar.getInstance();
                    Date fdate = discountBase.getDiscountStartTime();
                    cal.setTime(fdate);
                    cal.add(Calendar.HOUR,-discountBase.getPreStartHour());
                    fdate = cal.getTime();
                    addGoods.setPreStartTime(fdate);
                }
                addGoods.setDiscountGoodsRecommend(0);
                addGoods.setGoodsBuyCount(0);

                addGoods.setGoodsId(discountGoods.getGoodsId());
                addGoods.setGoodsName(discountGoods.getGoodsName());
                addGoods.setGoodsImage(discountGoods.getGoodsImage());
                addGoods.setGoodsPrice(discountGoods.getGoodsPrice());
                addGoods.setDiscountPrice(discountGoods.getDiscountPrice());
                addGoods.setCommonId(commonId);
                addGoods.setShopId(shopId);
                addGoods.setDiscountAmount(discountGoods.getDiscountAmount());

                if (null == param.getDiscountGoodsId()) {
                    activityDiscountGoodsMapper.insertDiscountGoods(addGoods);
                } else {
                    activityDiscountGoodsMapper.updateDiscountGoods(addGoods);
                }
                // 更新显示折扣字段//商品是否参加促销0不参加,1砍价,2秒杀,3限时折扣',

                if (null != commonId) {
                    Integer commonIsXian = 3;
                    Map<String,Object> param2 = new HashMap<>();
                    param2.put("commonIsXian",commonIsXian);
                    param2.put("commonId",commonId);
                    goodsServiceClient.updateCommonIsXian(param2);
                }
            }
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(), BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success();
    }

    @Override
    @Transactional
    public ResponseResult updateDiscountGoodsPrice(DiscountGoodsAddParamDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_PROMOTION_DISCOUNT, param.getToken());

        if (userPermissionsResult.getFlag()) {
            activityDiscountGoodsMapper.updateDiscountGoodsPrice(param);

        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(), BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryDiscountGoodsSpecList(DiscountBaseDetailQueryDTO param) {

        if (null == param.getCommonId() || null == param.getDiscountId()) {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.MISSING_PARAMETER.getMsg());
        }
        List<DiscountGoodsListVO> discountGoodsList = activityDiscountGoodsMapper.selectDiscountGoodsDetail2(param);

        if (org.springframework.util.CollectionUtils.isEmpty(discountGoodsList)) {
            discountGoodsList = Lists.newArrayList();
        }
        return ResponseResult.success(discountGoodsList);
    }

    @Override
    public ResponseResult selectPriceByGoodsId(Integer goodsId) {
        ModularGoodsVO modularGoodsVO = activityDiscountGoodsMapper.selectPriceByGoodsId(goodsId);
        return ResponseResult.success(modularGoodsVO);
    }

    @Override
    public ResponseResult queryDiscountBaseData(Map<String, Object> param) {
        if(null != param.get("discountId")){
            Integer discountId = (Integer) param.get("discountId");

            DiscountDataListVO result = new DiscountDataListVO();
            List<DiscountDataVO> dataList = new ArrayList<>();
            Integer allGoodsCount = 0;
            BigDecimal allDealAmount = BigDecimal.ZERO;
            Integer allNewerOrderNum = 0;
            Integer allOlderOrderNum = 0;

            IPage<DiscountGoodsListVO> page=this.baseMapper.queryDiscountGoodsInfo(new Query<DiscountGoodsListVO>().getPage(param),
                    param);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            Date startTime = calendar.getTime();
            calendar.add(Calendar.DATE,-1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);

            if(null != page && page.getRecords().size()>0){
                for(DiscountGoodsListVO discountGoodsListResult:page.getRecords()){
                    Map<Integer,Integer> newerNumMap = new HashMap<>();
                    Map<Integer,Integer> olderNumMap = new HashMap<>();
                    Integer goodsId = discountGoodsListResult.getGoodsId();
                    DiscountDataVO data = new DiscountDataVO();
                    data.setGoodsName(discountGoodsListResult.getGoodsName());
                    data.setSpecName(discountGoodsListResult.getSpecValueName());
                    if (calendar.getTime().before(discountGoodsListResult.getStartDateTime())){
                        discountGoodsListResult.setEndDateTime(discountGoodsListResult.getStartDateTime());
                    }else{
                        discountGoodsListResult.setEndDateTime(calendar.getTime());
                    }
                    discountGoodsListResult.setStartDateTime(startTime);
                    DiscountGoodsInfoVO discountGoodsInfo = this.baseMapper.queryDiscountGoodsInfo2(discountGoodsListResult);
                    if(null != discountGoodsInfo){
                        data.setDealAmount(discountGoodsInfo.getDealAmount());
                        data.setGoodsNum(discountGoodsInfo.getGoodsNum());
                        allGoodsCount = allGoodsCount + discountGoodsInfo.getGoodsNum();
                        allDealAmount = allDealAmount.add(discountGoodsInfo.getDealAmount());
                    }else{
                        data.setDealAmount(BigDecimal.ZERO);
                        data.setGoodsNum(0);
                    }
                    List<String> buyerUserIds =  this.baseMapper.queryBuyerUsers(discountGoodsListResult);
                    for(String userId:buyerUserIds) {
                        Map<String, Object> paramMap = new HashMap<>();
                        paramMap.put("userId", userId);
                        paramMap.put("startDateTime", discountGoodsListResult.getStartDateTime());
                        paramMap.put("shopId",discountGoodsListResult.getShopId());
                        paramMap.put("endDateTime",discountGoodsListResult.getEndDateTime());
                        paramMap.put("goodsId",discountGoodsListResult.getGoodsId());
                        paramMap.put("discountPrice",discountGoodsListResult.getDiscountPrice());

                        Integer olderCount = this.baseMapper.queryCountForOlder(paramMap);
                        Integer orderCount = this.baseMapper.queryUserOrderCount(paramMap);
                        if (null != olderCount) {
                            //新客
                            if (0 == olderCount) {
                                if(null == newerNumMap.get(goodsId)){
                                    newerNumMap.put(goodsId,orderCount);
                                }else{
                                    newerNumMap.put(goodsId,newerNumMap.get(goodsId)+orderCount);
                                }
                                allNewerOrderNum = allNewerOrderNum + orderCount;
                            } else {
                                if(null == olderNumMap.get(goodsId)){
                                    olderNumMap.put(goodsId,orderCount);
                                }else{
                                    olderNumMap.put(goodsId,olderNumMap.get(goodsId)+orderCount);
                                }
                                allOlderOrderNum = allOlderOrderNum + orderCount;
                            }
                        }
                    }

                    if(null != newerNumMap.get(goodsId)){
                        data.setNewerOrderNum(newerNumMap.get(goodsId));
                    }else{
                        data.setNewerOrderNum(0);
                    }

                    if(null != olderNumMap.get(goodsId)){
                        data.setOlderOrderNum(olderNumMap.get(goodsId));
                    }else{
                        data.setOlderOrderNum(0);
                    }


                    dataList.add(data);

                }
                result.setDataEntityList(dataList);
                result.setCount((int) page.getTotal());
                result.setAllDealAmount(allDealAmount);
                result.setAllNewerOrderNum(allNewerOrderNum);
                result.setAllOlderOrderNum(allOlderOrderNum);
                result.setAllGoodsCount(allGoodsCount);


            }
            return ResponseResult.success(result);
        }else{
            return ResponseResult.fail(BizCodeEnume.MISSING_PARAMETER);
        }
    }

    @Override
    public ResponseResult queryDiscountBaseDataExp(Map<String, Object> param) {
        String[] title = {"商品名称", "规格", "付款商品件数", "总成交额", "新客户下单数", "老客户下单数"};
        List<Map<String, String>> list = Lists.newArrayList();


        DiscountDataListVO result = new DiscountDataListVO();
        List<DiscountDataVO> dataList = new ArrayList<>();
        Integer allGoodsCount = 0;
        BigDecimal allDealAmount = BigDecimal.ZERO;
        Integer allNewerOrderNum = 0;
        Integer allOlderOrderNum = 0;
        IPage<DiscountGoodsListVO> page=this.baseMapper.queryDiscountGoodsInfo(new Query<DiscountGoodsListVO>().getPage(param),
                param);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        Date startTime = calendar.getTime();
        calendar.add(Calendar.DATE,-1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);


        if(null != page && page.getRecords().size()>0){
            for(DiscountGoodsListVO discountGoodsListResult:page.getRecords()){
                Map<Integer,Integer> newerNumMap = new HashMap<>();
                Map<Integer,Integer> olderNumMap = new HashMap<>();
                Integer goodsId = discountGoodsListResult.getGoodsId();
                DiscountDataVO data = new DiscountDataVO();
                data.setGoodsName(discountGoodsListResult.getGoodsName());
                data.setSpecName(discountGoodsListResult.getSpecValueName());
                if (calendar.getTime().before(discountGoodsListResult.getStartDateTime())){
                    discountGoodsListResult.setEndDateTime(discountGoodsListResult.getStartDateTime());
                }else{
                    discountGoodsListResult.setEndDateTime(calendar.getTime());
                }
                discountGoodsListResult.setStartDateTime(startTime);
                DiscountGoodsInfoVO discountGoodsInfo = this.baseMapper.queryDiscountGoodsInfo2(discountGoodsListResult);
                if(null != discountGoodsInfo){
                    data.setDealAmount(discountGoodsInfo.getDealAmount());
                    data.setGoodsNum(discountGoodsInfo.getGoodsNum());
                    allGoodsCount = allGoodsCount + discountGoodsInfo.getGoodsNum();
                    allDealAmount = allDealAmount.add(discountGoodsInfo.getDealAmount());
                }else{
                    data.setDealAmount(BigDecimal.ZERO);
                    data.setGoodsNum(0);
                }
                List<String> buyerUserIds = this.baseMapper.queryBuyerUsers(discountGoodsListResult);
                for(String userId:buyerUserIds) {
                    Map<String, Object> paramMap = new HashMap<>();
                    paramMap.put("userId", userId);
                    paramMap.put("startDateTime", discountGoodsListResult.getStartDateTime());
                    paramMap.put("shopId",discountGoodsListResult.getShopId());
                    paramMap.put("endDateTime",discountGoodsListResult.getEndDateTime());
                    paramMap.put("goodsId",discountGoodsListResult.getGoodsId());
                    paramMap.put("discountPrice",discountGoodsListResult.getDiscountPrice());

                    Integer olderCount = this.baseMapper.queryCountForOlder(paramMap);
                    Integer orderCount = this.baseMapper.queryUserOrderCount(paramMap);
                    if (null != olderCount) {
                        //新客
                        if (0 == olderCount) {
                            if(null == newerNumMap.get(goodsId)){
                                newerNumMap.put(goodsId,orderCount);
                            }else{
                                newerNumMap.put(goodsId,newerNumMap.get(goodsId)+orderCount);
                            }
                            allNewerOrderNum = allNewerOrderNum + orderCount;
                        } else {
                            if(null == olderNumMap.get(goodsId)){
                                olderNumMap.put(goodsId,orderCount);
                            }else{
                                olderNumMap.put(goodsId,olderNumMap.get(goodsId)+orderCount);
                            }
                            allOlderOrderNum = allOlderOrderNum + orderCount;
                        }
                    }
                }

                if(null != newerNumMap.get(goodsId)){
                    data.setNewerOrderNum(newerNumMap.get(goodsId));
                }else{
                    data.setNewerOrderNum(0);
                }

                if(null != olderNumMap.get(goodsId)){
                    data.setOlderOrderNum(olderNumMap.get(goodsId));
                }else{
                    data.setOlderOrderNum(0);
                }


                dataList.add(data);

            }

            for(DiscountDataVO data:dataList){
                HashMap<String, String> map = com.google.common.collect.Maps.newHashMap();
                map.put("商品名称", data.getGoodsName());
                map.put("规格", data.getSpecName());
                map.put("付款商品件数", data.getGoodsNum()+"");
                map.put("总成交额", data.getDealAmount()+"");
                map.put("新客户下单数", data.getNewerOrderNum()+"");
                map.put("老客户下单数", data.getOlderOrderNum()+"");


                list.add(map);

            }


            Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
             * 该list为每个sheet页的数据
             */> map = Maps
                    .newHashMap();
            map.put("测试合并数据", list);
            String url = ExcelsUtil.createExcel(title, map,
                    new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
            return ResponseResult.success(url);
        }else{
            return null;
        }
    }

    @Override
    public ResponseResult inactiveDiscountBase(Map<String, Object> param) {
        List<Integer> commonIdList =this.baseMapper.selectList(new LambdaQueryWrapper<ActivityDiscountGoodsEntity>()
                                    .eq(ActivityDiscountGoodsEntity::getDiscountId,param.get("discountId").toString()))
                                    .stream().map(ActivityDiscountGoodsEntity::getCommonId).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(commonIdList)) {
            // 获取其他正在进行的活动
            List<Integer> activeCommonIdList = this.baseMapper.selectActiveDiscountGoods(Integer.valueOf(param.get("discountId").toString()),
                    commonIdList.get(0));

            if (CollectionUtils.isEmpty(activeCommonIdList)) {
                this.baseMapper.updateCommonIsXian2(commonIdList);
            }

        }
        this.baseMapper.update(null,new LambdaUpdateWrapper<ActivityDiscountGoodsEntity>()
                        .set(ActivityDiscountGoodsEntity::getDiscountGoodsState,3)
                        .eq(ActivityDiscountGoodsEntity::getDiscountId,Integer.valueOf(param.get("discountId").toString())));

        activityDiscountBaseMapper.update(null,new LambdaUpdateWrapper<ActivityDiscountBaseEntity>()
                                  .set(ActivityDiscountBaseEntity::getDiscountState,3)
                                  .eq(ActivityDiscountBaseEntity::getDiscountId,Integer.valueOf(param.get("discountId").toString())));


        return ResponseResult.success();
    }


}

